#!/bin/bash
# 终止dev_pids文件中列出的所有进程

# 设置变量
PID_FILE="dev_pids"
LOG_FILE="kill_pids.log"

# 初始化日志
echo "[$(date)] 开始执行进程终止脚本" > "$LOG_FILE"

# 检查文件是否存在
if [ ! -f "$PID_FILE" ]; then
    echo "错误：未找到 $PID_FILE 文件" | tee -a "$LOG_FILE"
    exit 1
fi

# 检查文件是否为空
if [ ! -s "$PID_FILE" ]; then
    echo "错误：$PID_FILE 文件为空" | tee -a "$LOG_FILE"
    exit 1
fi

# 读取PID并终止进程
echo "正在读取 $PID_FILE 文件..." | tee -a "$LOG_FILE"
total=$(wc -l < "$PID_FILE")
processed=0
skipped=0
failed=0

while IFS= read -r pid || [ -n "$pid" ]; do
    # 验证PID格式
    if ! [[ "$pid" =~ ^[0-9]+$ ]]; then
        echo "跳过无效的PID: $pid" | tee -a "$LOG_FILE"
        ((skipped++))
        continue
    fi

    # 检查进程是否存在
    if ! ps -p "$pid" > /dev/null; then
        echo "PID $pid 不存在或已终止" | tee -a "$LOG_FILE"
        ((skipped++))
        continue
    fi

    # 尝试终止进程
    echo "正在终止进程 $pid..." | tee -a "$LOG_FILE"
    if kill -9 "$pid" 2>/dev/null; then
        echo "成功终止进程 $pid" | tee -a "$LOG_FILE"
        ((processed++))
    else
        echo "错误：无法终止进程 $pid" | tee -a "$LOG_FILE"
        ((failed++))
    fi
done < "$PID_FILE"

# 输出结果摘要
echo "------------------------" | tee -a "$LOG_FILE"
echo "处理结果:" | tee -a "$LOG_FILE"
echo "总PID数量: $total" | tee -a "$LOG_FILE"
echo "成功终止: $processed" | tee -a "$LOG_FILE"
echo "已跳过: $skipped" | tee -a "$LOG_FILE"
echo "失败: $failed" | tee -a "$LOG_FILE"
echo "[$(date)] 脚本执行完成" | tee -a "$LOG_FILE"

# 删除PID文件
if [ -f "$PID_FILE" ]; then
    rm "$PID_FILE"
    echo "已删除PID文件: $PID_FILE" | tee -a "$LOG_FILE"
fi

# 返回适当的退出状态
if [ "$failed" -gt 0 ]; then
    exit 2
else
    exit 0
fi